#!/usr/bin/env python3

# Copyright (c) 2020-2025 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import pathlib
from ._service import Service


class DaemonService(Service):

    @staticmethod
    def _name2UnitName(name):
        return name + ".service"

    @classmethod
    def _create(cls, parent, dir_path, name=None, unit_name=None, content=None):
        unit_name, content = cls._processArgs(name, unit_name, content)
        pathlib.Path(os.path.join(dir_path, unit_name)).write_text(content)
        return cls(parent, unit_name=unit_name)

    @classmethod
    def _exists(cls, parent, dir_path, name=None, unit_name=None, content=None):
        unit_name, content = cls._processArgs(name, unit_name, content)
        fullfn = os.path.join(dir_path, unit_name)
        if not os.path.exists(fullfn):
            return None
        if pathlib.Path(fullfn).read_text() != content:
            return None
        return cls(parent, unit_name=unit_name)

    def __init__(self, parent, name=None, unit_name=None):
        if name is not None:
            assert unit_name is None
            super().__init__(parent, self._name2UnitName(name))
        elif unit_name is not None:
            assert unit_name.endswith(".service")
            super().__init__(parent, unit_name)
        else:
            assert False

    @classmethod
    def _processArgs(cls, name, unit_name, content):
        if name is not None:
            assert unit_name is None
            unit_name = cls._name2UnitName(name)
            return (unit_name, content)

        if unit_name is not None:
            return (unit_name, content)

        assert False
